<template>
  <view class="flex flex-column justify-between">
    <view>
      <view class="mt-20">
        <sub-title class="mt-20" title="基础信息"> </sub-title>
        <view class="p-lr-40 mb-20">
          <view class="fz-30 lh-42 mt-20 flex justify-between border-bottom-CCCCCC pb-30" @tap="isShowHospitalSelect = true">
            <text class="fz-32 color-FF6262 w-14">*</text>
            <text class="w-200 color-333333 font-bold pl-20"> 所属医院</text>
            <view class="flex1 text-right color-888888">
              <!--       原始数据有值, isShowHospitalSelect只能为false       -->
              <u-input :value="formHospitalLabel" type="select" placeholder="选择医院" height="30" input-align="right" @click="isShowHospitalSelect = !oForm.hospitalId"/>
            </view>
          </view>
          <view class="fz-30 lh-42  mt-20 flex justify-between border-bottom-CCCCCC pb-30">
            <text class="fz-32 color-FF6262 w-14">*</text>
            <text class="w-200 font-bold color-333333 pl-20"> 所属科室</text>
            <view class="flex1 text-right color-888888">
              <!--       原始数据有值, isShowDepartmentSelect只能为false       -->
              <u-input :value="formDepartmentLabel" type="select" placeholder="选择科室" height="30" input-align="right" @click="isShowDepartmentSelect = !oForm.departmentId || allowEditDepartment"/>
            </view>
          </view>
          <view class="fz-30 lh-42  mt-20 flex justify-between border-bottom-CCCCCC pb-30">
            <text class="fz-32 color-FF6262 w-14">*</text>
            <text class="w-200 font-bold color-333333 pl-20"> 负责公司</text>
            <view class="flex1 text-right color-888888">
              <!--       原始数据有值, isShowCompanySelect只能为false       -->
              <u-input :value="formCompanyLabel" type="select" placeholder="选择公司" height="30" input-align="right" @click="isShowCompanySelect = !oForm.companyId"/>
            </view>
          </view>
          <view class="fz-30 lh-42  mt-20 flex justify-between border-bottom-CCCCCC pb-30">
            <text class="w-200 font-bold color-333333 pl-20">状态</text>
            <view class="flex1 text-right color-888888">
              <text>{{ statusLabel || '-' }}</text>
            </view>
          </view>
        </view>
        <view class="mt-20">
          <sub-title class="mt-20" title="设备信息"> </sub-title>
          <view class="p-lr-40 mb-20">
            <view class="lh-42 mt-20 flex">
              <view class="h-60 w-150 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center bg-2D8CF0 mr-20" @tap="gotoDeviceSelect">
                <text>选择设备</text>
              </view>
              <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center mr-50" @tap="resetDevice">
                <text>清除</text>
              </view>
            </view>
            <view class="fz-30 lh-42  mt-20 flex justify-between align-center">
              <text class="fz-32 color-FF6262 w-14">*</text>
              <text class="w-200 color-333333 font-bold">设备名称</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="form.deviceName" placeholder="点击输入设备名称" height="30" input-align="right" :disabled="!!form.deviceId" :maxlength="64"/>
              </view>
            </view>
            <view class="fz-30 lh-42 mt-20 flex justify-between align-center">
              <text class="w-200 color-333333 font-bold pl-14">设备编号</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="form.deviceNo" placeholder="点击输入设备编号" height="30" input-align="right" :disabled="!!form.deviceId" :maxlength="16"/>
              </view>
            </view>
            <view class="fz-30 lh-42 mt-20 flex justify-between align-center">
              <text class="w-180 color-333333 font-bold pl-14">分组房间</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="form.roomName" placeholder="点击输入分组房间" height="30" input-align="right" :disabled="!!form.deviceId" :maxlength="64"/>
              </view>
            </view>
          </view>
          <view class="mt-20">
            <sub-title class="mt-20" title="故障内容"></sub-title>
            <view class="p-lr-40 mb-20">
              <view class="fz-30 lh-42 mt-20">
                <text class="fz-32 color-FF6262 w-14">*</text><text class="w-200 color-333333 font-bold">故障描述</text>
                <view class="mt-10 border-CCCCCC w-full pt-12 pb-20 pl-10">
                  <textarea class="min-h-200 color-888888 fz-30" v-model="form.description" auto-height placeholder="请输入故障描述" placeholder-style="color:#CCCCCC;font-size:30rpx" maxlength="500" :show-confirm-bar="false" />
                </view>
              </view>

              <view class="fz-30 lh-42 mt-20 ">
                <text class="w-200 color-333333 font-bold">拍照</text>
                <view class="flex flex-wrap mt-20">
                  <!-- 图片缩略图 -->
                  <view class="relative mr-30" v-for="(item, index) in form.imageList" :key="index">
                    <image class="h-150 w-150" :data-cur="item.url" :src="item.url" @tap="previewImage"/>
                    <!--  移除图片的按钮  -->
                    <view class="absolute delBtn top-0 right-0" @tap.stop="removeImage(index)" >
                      <image class="h-50 w-50" src="@/static/images/workList/delPhoto.png"/>
                    </view>
                  </view>
                  <!-- 图片上传按钮 -->
                  <view v-if="form.imageList.length < 6" class="h-150 w-150 bg-CCCCCC flex align-center justify-center" @tap="uploadImage()">
                    <image class="h-50 w-50" src="@/static/images/workList/camera.png"></image>
                  </view>
                </view>
              </view>

              <view class="fz-30 lh-42 mt-20 flex justify-between" @tap="chooseSender">
                <text class="fz-32 color-FF6262 w-14">*</text><text class="w-200 color-333333 font-bold">报修人</text>
                <view class="flex1 flex text-right align-center justify-end color-888888">
                  <text>{{ form.initiator || '-' }}</text>
                  <image v-if="initiatorIsChoose" class="w-14 h-28 ml-20" src="@/static/images/common/toPath.png"></image>
                </view>
              </view>

              <view class="fz-30 lh-42 mt-20 flex justify-between">
                <text class="w-200 color-333333 font-bold">报修时间</text>
                <view class="flex1 text-right">
                  <text class="color-888888">
                    {{ form.createTime || '-' }}
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view v-if="showOperate" class="h-176 sticky bottom0 bg-fff pl-50 border-top-EEEEEE">
      <view class="flex align-center justify-end pt-30 pb-30">
        <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center mr-50" @tap="cancel">
          <text>取消</text>
        </view>
        <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center bg-2D8CF0 mr-50" @tap="confirm">
          <text>确定</text>
        </view>
      </view>
    </view>

    <!-- 提交数据-->
    <u-mask :show="isShowMask" :mask-click-able="false">
      <view class="flex justify-center align-center h-full color-fff fz-32 font-bold">
        <text>提交中...</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-mask>

    <u-select v-model="isShowHospitalSelect" :list="hospitalList" mode="single-column" value-name="hospitalId" label-name="name" @confirm="confirmHospitalId"/>
    <u-select v-model="isShowDepartmentSelect" :list="departmentList" mode="single-column" value-name="departmentId" label-name="name" @confirm="confirmDepartmentId"/>
    <u-select v-model="isShowCompanySelect" :list="companyList" mode="single-column" value-name="companyId" label-name="companyName" @confirm="confirmCompanyId"/>

    <!--图片加水印画板-->
    <canvas class="absolute top-99999"
            v-if="windowWidth !== 0 && windowHeight !== 0"
            :style="{'width':`${windowWidth}px`,'height': `${windowHeight}px`}"
            :canvas-id="`mycanvas`" >
    </canvas>

    <!--是否保存缓存弹窗-->
    <u-modal v-model="saveCacheModal" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 w-full">修改未提交，是否继续退出该页面？</view>
        <view class="w-full">
          <u-checkbox-group>
            <u-checkbox
                v-model="item.checked"
                v-for="(item, index) in isCache"
                :key="index"
                :name="item.name"
            >{{item.name}}</u-checkbox>
          </u-checkbox-group>
        </view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 w-120 h-60 border-box color-fff bg-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                @tap="saveCacheConfirm">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="saveCacheCancel">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

    <!--是否使用本地缓存弹窗-->
    <u-modal v-model="isUseCacheModal" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 border-bottom-CCCCCC w-full">本地有缓存，是否使用？</view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 w-120 h-60 border-box color-fff bg-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                @tap="setCacheToForm">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="isUseCacheModal = false">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

        <!--图片上传中模态框-->
    <!-- #ifndef MP-WEIXIN -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" v-model="isUploading">
      <view class="h-200 flex flex-column align-center justify-center font-bold color-888888 lh-33 bg-fff">
        <text class="mb-10">图片上传中</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-modal>
    <!-- #endif -->

    <!--微信小程序使用cover-view解决textarea层级过高问题-->

    <!-- #ifdef MP-WEIXIN -->
    <cover-view class="fixed top0 w-full min-100vh bg-00000060 flex align-center justify-center z-999"
      v-show="isUploading" @touchmove.stop.prevent="">
      <cover-view class="h-200 w-600 br-20 text-center lh-200 font-bold color-888888 lh-33 bg-fff">
        图片上传中
      </cover-view>
    </cover-view>
    <!-- #endif -->

  </view>
</template>

<script>
import uploadMaskImg from "@/mixins/uploadMaskImg";
import SubTitle from "@/components/SubTitle/SubTitle";
import {workOrderUpdate, workOrderDetail} from '@/api/repair/workOrder'
import {optionHospital} from '@/api/hospital/hospital'
import {optionDepartment} from '@/api/hospital/department'
import {companyOption} from '@/api/basic/company'
import {mapGetters} from 'vuex'
import { REP_WORK_ORDER_STATUS } from "@/utils/dict"

export default {
  name: "RepairWorkOrderToAcceptForm",
  mixins: [uploadMaskImg],
  components: {SubTitle},
  props: {
    workOrderId: {
      type: String,
      required: true
    },
    showOperate: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      loading: false,
      isShowMask: false,
      form: {},
      oForm: {},
      isShowHospitalSelect: false,
      hospitalList: [],
      isShowDepartmentSelect: false,
      departmentList: [],
      companyList: [],
      isShowCompanySelect: false,
      saveCacheModal:false, //是否保存数据弹框
      isUseCacheModal: false, //是否使用缓存弹窗
      isCache: [{
        name: '暂存该页面信息',
        checked: true
      }],
      //图片上传
      isUploading: false,
      applyCache:false,
      allowEditDepartment: false,
      initiatorIsChoose:false
    }
  },
  computed: {
    statusLabel(){
      const valueList = Object.values(REP_WORK_ORDER_STATUS)
      return valueList.find(item => item.value === this.form.status)?.label
    },
    formHospitalLabel() {
      return this.hospitalList.find(item => item.hospitalId === this.form.hospitalId)?.name || ''
    },
    formDepartmentLabel() {
      return this.departmentList.find(item => item.departmentId === this.form.departmentId)?.name || ''
    },
    formCompanyLabel() {
      return this.companyList.find(item => item.companyId === this.form.companyId)?.companyName || ''
    },
    ...mapGetters(['getFixCacheByWorkOrderId'])
  },
  created() {
    this.allowEditDepartment = this.$auth.hasRoleOr(['manager', 'admin'])
    this.isUseCacheModal = this.getFixCacheByWorkOrderId(this.workOrderId) ? true : false
    this.init()
  },
  methods: {
    init() {
      this.resetForm()
      return this.getDetail().then(() => Promise.all([
        this.getHospitalList(),
        this.getDepartmentList(),
        this.getCompanyList()
      ]))
    },
    getDetail() {
      this.loading = true
      return workOrderDetail(this.workOrderId).then(res => {
        this.form = res.data
        this.initiatorIsChoose = this.form.initiatorUserId===-1
        this.setoForm(res.data)
        this.loading = false
        return Promise.resolve(res)
      })
    },
    resetForm() {
      const defaultForm = {
        companyId: "",
        companyName: "",
        content: null,
        createTime: "",
        departmentId: "",
        departmentName: "",
        description: "",
        deviceId: "",
        deviceName: "",
        deviceNo: "",
        endTime: null,
        handbook: null,
        hospitalId: "",
        hospitalName: "",
        imageList: [],
        initiator: "",
        initiatorUserId: "",
        recordId: null,
        recordImageList: null,
        recordPartList: null,
        repairStaff: null,
        responsibleStaff: null,
        responsibleStaffIds: null,
        roomName: "",
        staffIds: null,
        startTime: null,
        status: "0",
        workOrderId: this.workOrderId
      }
      this.form = {...defaultForm}
    },
    resetDevice() {
      this.form.deviceId = ''
      this.form.deviceName = ''
      this.form.deviceNo = ''
      this.form.roomName = ''
    },
    /** 查询医院列表 */
    getHospitalList() {
      return optionHospital().then(res => {
        this.hospitalList = res.data
        return Promise.resolve(res)
      })
    },
    /** 所属医院改变, 清空所属科室, 并重新获取新的所属科室列表 */
    onHospitalChange() {
      if (this.form.departmentId) {
        this.form.departmentId = ''
      }
      if (this.form.companyId) {
        this.form.companyId = ''
      }
      this.getDepartmentList()
      this.getCompanyList()
    },
    confirmHospitalId([{value: hospitalId}]) {
      if (hospitalId) {
        this.form.hospitalId = hospitalId
      }
      this.onHospitalChange()
    },
    /** 查询科室列表(依赖所属医院) */
    getDepartmentList() {
      if (!this.form.hospitalId) {
        this.departmentList = []
        return Promise.resolve('医院id为空')
      }
      return optionDepartment({hospitalId: this.form.hospitalId}).then(res => {
        this.departmentList = res.data
        return Promise.resolve(res)
      })
    },
    confirmDepartmentId([{value: departmentId}]) {
      if (!departmentId || departmentId !== this.form.departmentId) {
        this.resetDevice()
      }
      if (departmentId) {
        this.form.departmentId = departmentId
      }
    },
    getCompanyList() {
      if (!this.form.hospitalId) {
        this.companyList = []
        return Promise.resolve('医院id为空')
      }
      companyOption({hospitalId: this.form.hospitalId}).then(res => {
        this.companyList = res.data
        return Promise.resolve(res)
      })
    },
    confirmCompanyId([{value: companyId}]) {
      if (companyId) {
        this.form.companyId = companyId
      }
    },
    gotoDeviceSelect() {
      if (!this.form.hospitalId || !this.form.departmentId) {
        this.$u.toast('请先选择医院和科室')
        return
      }
      uni.navigateTo({
        url: `/pages/repair/choose-device?hospitalId=${this.form.hospitalId}&departmentId=${this.form.departmentId}&deviceId=${this.form.deviceId || ''}`,
        events: {
          confirm: (data) => {
            this.form.deviceId = data.deviceId
            this.form.deviceNo = data.deviceNo
            this.form.deviceName = data.deviceName
            this.form.roomName = data.roomName
          }
        },
      })
    },
    //选择人员-获取人员列表
    chooseSender () {
      if(this.initiatorIsChoose){
        uni.navigateTo({
          url: `/pages/repair/choose-initiator-user?hospitalId=${this.form.hospitalId}`,
          events: {
            getStaff: (data) => {
              const staff = data.staff
              if(staff && staff.staffName && staff.userId){
                this.form.initiator = staff.staffName
                this.form.initiatorUserId = staff.userId
              }
            }
          }
        })
      }
    },
    // 点击预览
    previewImage (e) {
      const current = e.currentTarget.dataset.cur;
      const urls = this.form.imageList.map(el => el.url);
      uni.previewImage({
        current: current,
        urls: urls, //需要预览的图片链接列表
        indicator: "none", //图片指示器样式 "default" - 底部圆点指示器； "number" - 顶部数字指示器； "none" - 不显示指示器
      });
    },
    // 删除图片
    removeImage (index) {
      this.form.imageList.splice(index, 1)
    },
    // 上传图片
    uploadImage() {
      this.uploadMaskImg({sourceType: ['album', 'camera']})
    },
    // 上传图片成功回调(uploadMaskImg的方法重写)
    uploadSuccessCallback({data}) {
      this.form.imageList.push({
        url: data.url,
        ossId: data.ossId,
      })
    },
    // 水印内容(uploadMaskImg的方法重写)
    maskContent (ctx, image) {
      // ctx.strokeText(this.form.deviceName || '-', image.width * 0.092, image.width * 0.23);
      // ctx.fillText(this.form.deviceName || '-', image.width * 0.092, image.width * 0.23)
      //
      // ctx.strokeText(this.$store.getters.staffName || '-', image.width * 0.092, image.width * 0.28);
      // ctx.fillText(this.$store.getters.staffName || '-', image.width * 0.092, image.width * 0.28)
      //
      // ctx.strokeText(dayjs().format('YYYY-MM-DD HH:mm:ss'), image.width * 0.092, image.width * 0.33);
      // ctx.fillText(dayjs().format('YYYY-MM-DD HH:mm:ss'), image.width * 0.092, image.width * 0.33)
    },
    validate() {
      if (!this.form.hospitalId) {
        this.$u.toast('所属医院不能为空')
        return false
      }
      if (!this.form.departmentId) {
        this.$u.toast('所属科室不能为空')
        return false
      }
      if (!this.form.companyId) {
        this.$u.toast('负责公司不能为空')
        return false
      }
      if (!this.form.deviceName) {
        this.$u.toast('设备名称不能为空')
        return false
      }
      if (!this.form.description) {
        this.$u.toast('故障描述不能为空')
        return false
      }
      // if (!this.form.initiator) {
      //   this.$u.toast('报修人不能为空')
      //   return false
      // }
      return true
    },
    confirm() {
      if (this.loading) {return}
      if (!this.validate()) {return}
      this.form.ossIdList = this.form.imageList.map(el => el.ossId).filter(el => el)
      this.loading = true
      uni.showLoading({title: '提交中'})
      workOrderUpdate(this.form).then(() => {
        this.$store.dispatch('removeCacheOfWorkOrderId',this.form.workOrderId )
        this.$emit('confirm')
      }).finally(() => {
        this.loading = false
        uni.hideLoading()
      })
    },
    setoForm(data){
      this.oForm.hospitalId = data.hospitalId
      this.oForm.departmentId = data.departmentId
      this.oForm.companyId = data.companyId
      this.oForm.deviceId = data.deviceId
      this.oForm.deviceName = data.deviceName
      this.oForm.deviceNo = data.deviceNo
      this.oForm.description = data.description
      this.oForm.imageList = JSON.parse(JSON.stringify(data.imageList))
      this.oForm.initiator = data.initiator
      this.oForm.initiatorUserId = data.initiatorUserId
    },
    setCacheToForm(){
      const fixCache = this.getFixCacheByWorkOrderId(this.workOrderId)
      if(fixCache){
        this.form.hospitalId = fixCache.hospitalId
        this.form.departmentId = fixCache.departmentId
        this.form.companyId = fixCache.companyId
        this.form.deviceId = fixCache.deviceId
        this.form.deviceName = fixCache.deviceName
        this.form.deviceNo = fixCache.deviceNo
        this.form.description = fixCache.description
        this.form.imageList = JSON.parse(JSON.stringify(fixCache.imageList))
        this.form.initiator = data.initiator
        this.form.initiatorUserId = data.initiatorUserId
        this.applyCache = true
      }
      this.isUseCacheModal = false
    },
    saveCacheConfirm(){
      const cacheData = {
        hospitalId : this.form.hospitalId,
        departmentId : this.form.departmentId,
        companyId : this.form.companyId,
        deviceId : this.form.deviceId,
        deviceName : this.form.deviceName,
        deviceNo : this.form.deviceNo,
        description : this.form.description,
        imageList : this.form.imageList,
        initiatorUserId: this.form.initiatorUserId,
        initiator: this.form.initiator
      }
      this.$store.dispatch('setFixCacheOfWorkOrderId',{ id : this.form.workOrderId, cacheData})
      .catch((res)=>{
      })
      .finally(()=>{
        this.saveCacheModal = false
        this.$emit('cancel')
      })
    },
    cancel() {
      const keys = Object.keys(this.oForm)
      let isEqual = false
      if(this.applyCache){
        const cacheData = this.getFixCacheByWorkOrderId(this.workOrderId)
        isEqual = keys.every(key=>cacheData[key]?.toString()===this.form[key]?.toString())
      }else{
        isEqual = keys.every(key=>this.oForm[key]?.toString()===this.form[key]?.toString())
      }
      if(!isEqual){
        this.saveCacheModal = true
      }else{
        this.$emit('cancel')
      }
    },
    saveCacheCancel(){
      this.saveCacheModal = false
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="scss">
.edit {
  background: rgba(45, 140, 240, 0.1);
  border-radius: 5rpx;
  opacity: 1;
  border: 1rpx solid #2D8CF0;
  color: #2D8CF0;
}

/deep/.u-tab-bar {
  bottom: -10rpx !important;
  z-index: 9;
}

/deep/ .u-collapse-head {
  margin-bottom: 0 !important;
  border-bottom: 1px solid #ccc;
  padding: 0 !important;
  padding-bottom: 30rpx !important;
  padding-top: 20rpx !important;
}
</style>
